<template>
  <el-popover placement="bottom" width="400" trigger="click">
    <template>
      <el-tabs v-model="activeName" @tab-click="handleClick" stretch>
        <el-tab-pane :label="msg1Title" name="1">
          <div class="noticeItem" :key="index" v-for="(record, index) in notice1">
            <div style="margin-left: 5%;width: 50%">
              <p><a @click="showNotice(record)">{{ record.noticeTitle }}</a></p>
              <p style="color: rgba(0,0,0,.45);margin-bottom: 0px">{{ record.createTime }} 发布</p>
            </div>
            <div>
              <el-tag @click="showNotice(record)" v-if="record.priority === 'L'" effect="dark"
                type="primary">一般消息</el-tag>
              <el-tag @click="showNotice(record)" v-if="record.priority === 'M'" effect="dark"
                type="warning">重要消息</el-tag>
              <el-tag @click="showNotice(record)" v-if="record.priority === 'H'" effect="dark"
                type="danger">紧急消息</el-tag>
            </div>
          </div>
          <el-empty v-if="notice1.length === 0" description="暂无数据"></el-empty>
          <div style="margin-top: 5px;text-align: center">
            <el-button @click="toMyNotice()" type="text" block>查看更多</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="msg2Title" name="2">
          <div class="noticeItem" :key="index" v-for="(record, index) in notice2">
            <div style="margin-left: 5%;width: 50%">
              <p><a @click="showNotice(record)">{{ record.noticeTitle }}</a></p>
              <p style="color: rgba(0,0,0,.45);margin-bottom: 0px">{{ record.createTime }} 发布</p>
            </div>
            <div>
              <el-tag @click="showNotice(record)" v-if="record.priority === 'L'" effect="dark"
                type="primary">一般消息</el-tag>
              <el-tag @click="showNotice(record)" v-if="record.priority === 'M'" effect="dark"
                type="warning">重要消息</el-tag>
              <el-tag @click="showNotice(record)" v-if="record.priority === 'H'" effect="dark"
                type="danger">紧急消息</el-tag>
            </div>
          </div>
          <el-empty v-if="notice2.length === 0" description="暂无数据"></el-empty>
          <div style="margin-top: 5px;text-align: center">
            <el-button @click="toMyNotice()" type="text" block>查看更多</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="msg3Title" name="3">
          <div class="noticeItem" :key="index" v-for="(record, index) in notice3">
            <div style="margin-left: 5%;width: 50%">
              <p><a @click="showNotice(record)">{{ record.noticeTitle }}</a></p>
              <p style="color: rgba(0,0,0,.45);margin-bottom: 0px">{{ record.createTime }} 发布</p>
            </div>
            <div>
              <el-tag @click="showNotice(record)" v-if="record.priority === 'L'" effect="dark"
                type="primary">一般消息</el-tag>
              <el-tag @click="showNotice(record)" v-if="record.priority === 'M'" effect="dark"
                type="warning">重要消息</el-tag>
              <el-tag @click="showNotice(record)" v-if="record.priority === 'H'" effect="dark"
                type="danger">紧急消息</el-tag>
            </div>
          </div>
          <el-empty v-if="notice3.length === 0" description="暂无数据"></el-empty>
          <div style="margin-top: 5px;text-align: center">
            <el-button @click="toMyNotice()" type="text" block>查看更多</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </template>
    <el-badge :value="msgTotal" slot="reference">
      <i class="el-icon-message-solid">
      </i>
    </el-badge>
    <show-notice ref="ShowNotice"></show-notice>
  </el-popover>
</template>

<script>
import { listByUser, updateUserIdAndNotice } from "@/api/system/notice";
import ShowNotice from './ShowNotice.vue';
export default {
  name: "HeaderNotice",
  components: { ShowNotice },
  data() {
    return {
      loading: false,
      activeName: '1',
      notice1: [],
      notice2: [],
      notice3: [],
      msg1Count: "0",
      msg2Count: "0",
      msg3Count: "0",
      msg1Title: "通知(0)",
      msg2Title: "",
      msg3Title: "",
      websock: null,
      lockReconnect: false,
    }
  },
  computed: {
    msgTotal() {
      return parseInt(this.msg1Count) + parseInt(this.msg2Count) + parseInt(this.msg3Count);
    }
  },
  mounted() {
    this.loadData();
    this.initWebSocket();
  },
  destroyed() { // 离开页面生命周期函数
    this.websocketOnclose();
  },
  methods: {
    loadData() {
      try {
        // 获取系统消息
        listByUser().then(res => {
          if (res.code == 200) {
            this.notice1 = res.data.anntMsgList;
            this.msg1Count = res.data.anntMsgTotal;
            this.msg1Title = "通知(" + res.data.anntMsgTotal + ")";
            this.notice2 = res.data.sysMsgList;
            this.msg2Count = res.data.sysMsgTotal;
            this.msg2Title = "系统消息(" + res.data.sysMsgTotal + ")";
            this.notice3 = res.data.todealMsgList;
            this.msg3Count = res.data.todealMsgTotal;
            this.msg3Title = "待办消息(" + res.data.todealMsgTotal + ")";
          }
        }).catch(error => {
          console.log("系统消息通知异常", error); //这行打印permissionName is undefined
        });
      } catch (error) {
        console.log("通知异常", err);
      }
    },
    handleClick() {
      console.log('🚀 ~ file: index.vue:22 ~ data ~ activeName:', this.activeName)
    },
    initWebSocket() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var uid = this.$store.state.user.name;
      var url = process.env.VUE_APP_WS_API + "/websocket/" + uid;
      console.log("url=", url);
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
    },
    websocketOnopen() {
      console.log("WebSocket连接成功");
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnerror(e) {
      console.log("WebSocket连接发生错误");
      this.reconnect();
    },
    websocketOnmessage(e) {
      console.log("-----接收消息-------", e);
      console.log("-----接收消息-------", e.data);
      const data = JSON.parse(e.data)
      this.$notify({
        title: '您有一条新消息',
        message: data.msgTxt,
        duration: 0
      });
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnclose(e) {
      console.log("connection closed (" + e + ")");
      if (e) {
        console.log("connection closed (" + e.code + ")");
      }
      this.reconnect();
    },
    showNotice(record) {
      updateUserIdAndNotice({
        noticeId: record.noticeId
      }).then((res) => {
        if (res.code == 200) {
          this.loadData();
        }
      });
      this.$refs.ShowNotice.detail(record);
    },
    toMyNotice() {
      this.$router.push({
        path: '/personal/mynotice'
      });
    },
    reconnect() {
      if (this.lockReconnect) return;
      this.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        this.initWebSocket();
        this.lockReconnect = false;
      }, 5000);
    },
  }
}
</script>

<style scoped lang="scss">
.noticeItem {
  display: flex;
  align-items: baseline;
  justify-content: space-between;

  border-bottom: 1px solid #f0f0f0;
}

::v-deep .el-badge__content.is-fixed {
  top: 10px;
}
</style>